<!--
 * @author luguoxiang
 * @date 2022/9/17
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <slot :open="open" :show-info="showInfo">
    <t-input
      v-if="input"
      ref="inputRef"
      :value="showInfo"
      v-bind="$attrs"
      readonly
      :disabled="disabled"
      @click="open"
    />
  </slot>
  <t-dialog
    v-if="opened"
    v-model:visible="visible"
    header="选择职位"
    width="550px"
    mode="modeless"
    class="lg-modal post-picker-modal"
    draggable
    @confirm="ok"
    @closed="closed"
  >
    <div class="post-picker">
      <t-input
        placeholder="搜索职位"
        :value="keyword"
        style="margin-bottom: var(--app-space-vertical)"
        @change="search"
      />
      <div v-show="keyword" class="post-picker-user">
        <radio-list :list="userList" :value="selection.id" @change="change" />
      </div>
      <t-tabs v-show="!keyword" v-model:value="type" class="gl-tabs-auto-h">
        <t-tab-panel value="LAST" label="最近" :destroy-on-hide="false">
          <div style="margin-bottom: var(--app-space-vertical)"></div>
          <radio-list :list="lastList" :value="selection.id" @change="lastchange" />
        </t-tab-panel>
        <t-tab-panel value="ORG" label="组织机构" :destroy-on-hide="false">
          <t-tree :data="orgList" line :load="loadByOrg" expand-on-click-node hover>
            <template #label="{ node: { data } }">
              <t-radio v-if="data.type === 'POST'" :checked="selection.id === data.id" @change="treechange(data)">
                {{ data.name }}
              </t-radio>
              <template v-else>
                <span :class="'inner-tag-' + data.other">
                  <lg-text options="OrgTypeEnum" :model-value="data.other" />
                </span>
                {{ data.name }}
              </template>
            </template>
          </t-tree>
        </t-tab-panel>
      </t-tabs>
    </div>
    <template #footer>
      <div style="display: flex">
        <div class="post-picker-item">
          已选：
          <template v-if="selection.id">
            {{ selection.name }}<span class="gl-color-placeholder">（{{ selection.other }}）</span>
            <lg-icon value="close" @click="remove()" />
          </template>
        </div>
        <t-button variant="outline" @click="visible = false"> 取消 </t-button>
        <t-button @click="ok">确定</t-button>
      </div>
    </template>
  </t-dialog>
</template>
<script setup lang="ts">
import { nextTick, ref, watch } from 'vue';
import { debounce, distinct, LgIcon, LgText } from '@/soar';
import RadioList from './RadioList.vue';
import api from './api';

const props = defineProps({
  modelValue: {
    type: String,
  },
  /**
   * 是否只读
   */
  readonly: {
    type: Boolean,
    default: false,
  },
  /**
   * 是否禁用
   */
  disabled: {
    type: Boolean,
    default: false,
  },
  /**
   * 是否输入框形式
   */
  input: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(['ok', 'change', 'update:modelValue']);
const opened = ref(false);
const visible = ref(false);
const type = ref('LAST');
const keyword = ref();
const userList = ref([]);
const lastList = ref([]);
const orgList = ref([]);
const selection = ref({});
const showInfo = ref('');
const inputRef = ref();

function closed() {
  opened.value = false;
  inputRef.value?.blur?.();
}

function change(e: any) {
  selection.value = userList.value.find((x) => x.id === e);
}

function lastchange(e: any) {
  selection.value = lastList.value.find((x) => x.id === e);
}

function treechange(e) {
  selection.value = e;
}

function remove() {
  selection.value = {};
}

const queryUser = debounce(() => {
  api.query(keyword.value).then((res) => {
    userList.value = res;
  });
}, 250);

function search(e) {
  keyword.value = e;
  if (!keyword.value) {
    userList.value = [];
    return;
  }
  queryUser();
}

function loadByOrg({ data: { id } }) {
  return api.org(id).then((res) => {
    for (const x of res) {
      if (x.type === 'POST') {
        x.value = x.id;
      } else {
        x.value = `o:${x.id}`;
        x.children = x.descendantQuantity > 0;
      }
      delete x.descendantQuantity;
    }
    return res;
  });
}

/**
 * 点击确定时
 */
function ok() {
  putLast();
  emits('ok', selection.value);
  if (props.input) {
    emits('change', selection.value.id);
    emits('update:modelValue', selection.value.id);
  }
  nextTick(() => {
    showInfo.value = selection.value.name;
    visible.value = false;
  });
}

function putLast() {
  if (selection.value.id) {
    let res = distinct([selection.value.id].concat(lastList.value.map((x) => x.id)), (x) => x);
    if (res.length > 50) {
      res = res.slice(0, 50);
    }
    localStorage.setItem('post-picker', res.join(','));
  }
}

watch(
  () => props.modelValue,
  (v) => {
    if (!opened.value && v) {
      api.ids(v).then((res) => {
        showInfo.value = res[0].name;
      });
    }
  },
  { immediate: props.input },
);

function open(params: any) {
  if (props.disabled || props.readonly) {
    return;
  }
  opened.value = true;
  keyword.value = null;
  loadByOrg({ data: { id: 0 } }).then((res) => {
    orgList.value = res;
  });
  let ls: string[];
  try {
    ls = localStorage.getItem('post-picker')?.split(',');
    if (!Array.isArray(ls)) {
      ls = [];
    }
  } catch (e) {
    localStorage.removeItem('post-picker');
    ls = [];
  }
  const ids = props.modelValue ? [props.modelValue].concat(ls) : ls;
  if (ids.length) {
    api
      .ids(distinct(ids, (x) => x))
      .then((res) => {
        selection.value = res.find((x) => x.id === props.modelValue) || {};
        lastList.value = res.filter((x) => ls.includes(x.id));
        if (!lastList.value?.length) {
          type.value = 'ORG';
        }
      })
      .catch((err) => {
        if (err.response.status === 400) {
          localStorage.removeItem('post-picker');
        }
      });
  }
  nextTick(() => {
    visible.value = true;
  });
}

defineExpose({
  open,
});
</script>
<script lang="ts">
export default {
  name: 'PostSinglePicker',
};
</script>
<style lang="less" scoped>
.post-picker {
  .t-tabs,
  .post-picker-user {
    height: 60vh;
  }
  .post-picker-user {
    overflow-y: auto;
  }
  .inner-tag-0 {
    color: var(--app-color-primary-5);
  }
  .inner-tag-1 {
    color: var(--app-color-primary);
  }
  .inner-tag-2 {
    color: var(--td-warning-color);
  }
  .inner-tag-3 {
    color: var(--td-success-color);
  }
}
.post-picker-item {
  flex: 1;
  text-align: left;
  line-height: 32px;
  .t-icon-close {
    display: none;
    color: red;
    font-size: 22px;
    transition: font-size;
  }
  &:hover {
    .t-icon-close {
      display: unset;
    }
  }
}
</style>
